package com.qing.utils.lottery.ssq;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.qing.utils.lottery.ssq.bean.SsqResponse;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

public class SsqQueryUtil {
//    https://jc.zhcw.com/port/client_json.php?callback=jQuery112203309370653671926_1692437776268&transactionType=10001001&lotteryId=1&issueCount=1000&startIssue=&endIssue=&startDate=&endDate=&type=0&pageNum=1&pageSize=30&tt=0.31727756518270267&_=1692437776273

    public static void main(String[] args) {
        SsqResponse ssqResponse = querySsqWinningList(10000);
        System.out.println(JSONUtil.toJsonPrettyStr(ssqResponse));

        System.out.printf("双色球pageCount=[%s], countNum=[%s], resultSize=[%s]%n", ssqResponse.getPageNum(), ssqResponse.getCountNum(), ssqResponse.getResult().size());
        saveSsqData(ssqResponse);
    }

    private static SsqResponse querySsqWinningList(int count) {
        String ssqQueryUrl = "https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueStart=&issueEnd=&dayStart=&dayEnd=&issueCount="+10000;
//        String ssqQueryUrl = "http://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice?name=ssq&issueStart=&issueEnd=&dayStart=&dayEnd=&pageNo=1&pageSize=30&systemType=PC&issueCount=" + count;
        String s = HttpUtil.get(ssqQueryUrl);
        HttpRequest httpRequest = HttpUtil.createGet(ssqQueryUrl).contentType(ContentType.JSON.getValue());
        System.out.println("============双色球");
        String body;
        try (HttpResponse response = httpRequest.execute()) {
            body = response.body();
//            System.out.println(body);
            System.out.println("============双色球");
            SsqResponse ssqResponse = JSONUtil.toBean(body, SsqResponse.class);
            return ssqResponse;
        }
    }

    private static void saveSsqData(SsqResponse ssqResponse) {
        String rootPath = "D:\\Workspaces\\MySpace\\IDEA\\common-utils\\lottery-utils\\src\\main\\resources";
        String dir = "ssqResponse";
        File dataDir = new File(rootPath, dir);
        if (!dataDir.exists()) {
            boolean mkdir = dataDir.mkdir();
            int tryCount = 10;
            while (!mkdir && tryCount-- > 0) {
                mkdir = dataDir.mkdir();
            }
        }

        String fileName = "ssqResponse_" + LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyyy-MM-dd_HH_mm_ss");

        FileUtil.writeBytes(JSONUtil.toJsonPrettyStr(ssqResponse).getBytes(StandardCharsets.UTF_8), new File(dataDir, fileName));


    }

}
